//package main
//
//import (
//	"a_plus_station/tables"
//	"gorm.io/driver/mysql"
//	"gorm.io/gorm"
//	"gorm.io/gorm/schema"
//)
//
//func main() {
//	db, err := gorm.Open(mysql.Open("root:123456@tcp(192.168.0.10:3306)/a_plus_station?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{NamingStrategy: schema.NamingStrategy{
//		SingularTable: true, // 不加这个会用model的名字加上 s 当做表名字
//	}})
//	if err != nil {
//		panic("failed to connect database")
//	}
//
//	err = db.AutoMigrate(&tables.User{}, &tables.UserLogin{}, &tables.Category{}, &tables.Goods{}, &tables.GoodsDesc{}, &tables.Collect{}, &tables.Order{}, &tables.Placard{})
//	if err != nil {
//		return
//	}
//}

package main

import (
	"a_plus_station/tables"
	"fmt"
	"github.com/tealeg/xlsx"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"log"
	"math"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"
)

func checkFloat(number float64) float64 {
	if math.IsNaN(number) {
		return 0.00
	}
	return number
}

func GetMainImage(str []string) string {
	for _, s := range str {
		// 检查字符串中是否包含 "-"
		if !strings.Contains(s, "-") {
			return s
		}
	}
	return str[0]
}

func GetPathImage(dirPath string) ([]string, error) {
	var imagePath []string
	dir, err := os.Open(dirPath)
	if err != nil {
		fmt.Println("Error opening directory:", err)
		return nil, err
	}
	defer func(dir *os.File) {
		err := dir.Close()
		if err != nil {

		}
	}(dir)

	files, err := dir.Readdir(-1)
	if err != nil {
		fmt.Println("Error reading directory:", err)
		return nil, err
	}

	for _, file := range files {
		if !file.IsDir() && (strings.HasSuffix(strings.ToLower(file.Name()), ".webp")) {
			iP := filepath.Join(dirPath, file.Name())
			newPath := strings.Replace(iP, "E:\\nginx-1.24.0\\html", "http://127.0.0.1", 1)
			newPath = strings.Replace(newPath, "\\", "/", -1)
			imagePath = append(imagePath, newPath)
		}
	}
	// E:\nginx-1.24.0\html\image_all\APMJ320\APMJ320.webp
	return imagePath, nil
}

func splitColor2string(colors ...string) string {
	var result string
	for i, color := range colors {
		colorTrim := strings.TrimSpace(color)
		if colorTrim == "" {
			continue
		}
		if i > 0 {
			result += ","
		}
		result += colorTrim
	}
	return result
}

func main() {
	db, err := gorm.Open(mysql.Open("root:123456@tcp(192.168.0.10:3306)/a_plus_station?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{NamingStrategy: schema.NamingStrategy{
		SingularTable: true, // 不加这个会用model的名字加上 s 当做表名字
	}})
	if err != nil {
		log.Fatal("failed to connect database")
	}

	cate := []string{"Apparel & Outerwear",
		"Baby, Toddler, & Child Items",
		"Bags & Luggage",
		"Caps & Hats",
		"Drinkware",
		"Toys, Games, & Novelties",
		"Pet Supplies",
		"School, Office, & Craft Supplies",
		"Sports, Fitness, & Outdoors",
		"Writing Instruments",
		"Home & Garden",
		"Key Chains",
		"Kitchen & Dining",
		"Party Supplies",
		"Health, Beauty & Wellness",
		"Holiday & Religious Items",
		"Jewelry and Accessories",
		"Lanyards, Badges, & Badge Holders",
		"Signs, Banners, Flags, & Displays",
		"Tools & Hardware",
		"Equipment and Business Services",
		"Food, Beverage, & Tobacco",
		"Magnets & Buttons, Stickers & Decals",
		"Electronics & Tech Products",
		"Automotive Accessories",
		"Awards & Trophies",
		"Publications",
		"Storage & Organization",
		"Other",
	}

	BDB := db.Begin()
	for _, i2 := range cate {
		ressult := BDB.Create(&tables.Category{
			Name:      i2,
			ImageUrl:  fmt.Sprintf("http://127.0.0.1/category/%s.webp", i2),
			BaseModel: tables.BaseModel{},
		})
		if ressult.Error != nil {
			panic(ressult.Error.Error())
		}
	}
	BDB.Commit()

	// 自动迁移模式
	//db.AutoMigrate(&Goods{})

	// 打开 Excel 文件
	xlFile, err := xlsx.OpenFile("D:\\money\\a_plus_station\\test\\APMJ320-APMJ612.xlsx")
	if err != nil {
		log.Fatal("Error opening file:", err)
	}

	// 获取 InfoImport 表
	sheet := xlFile.Sheet["InfoImport"]
	if sheet == nil {
		log.Fatal("Sheet InfoImport not found")
	}

	rootImagePath := "E:\\nginx-1.24.0\\html"
	for index, row := range sheet.Rows {
		if index == 0 {
			continue
		}
		if row != nil {
			//GoodsID: row.Cells[0].String(), // 假设 A 列是 GoodsID
			//					Name:    row.Cells[1].String(), // 假设 B 列是 Name
			//					Desc:    row.Cells[2].String(), // 假设 C 列是 Desc
			// http://127.0.0.1/image_x/APMJ320/APMJ320.webp
			GoodsID := row.Cells[3].String()

			OutMaxPriceTemp, _ := row.Cells[64].Float()
			OutMaxPrice := int32(OutMaxPriceTemp * 100)

			OutMinPriceTemp, _ := row.Cells[78].Float()
			OutMinPrice := int32(OutMinPriceTemp * 100)

			MainPicture := path.Join(rootImagePath, GoodsID)
			imageArray, _ := GetPathImage(MainPicture)

			t := time.Now().UTC().Format(tables.FormatTime)
			fptTime, err := time.ParseInLocation(tables.FormatTime, t, time.Local)
			if err != nil {
				panic("时间格式化出错")
			}
			CreatedAt := &tables.MyTime{Time: fptTime}
			goods := tables.Goods{
				GoodsID:      GoodsID,
				CategoryID:   1,
				Name:         row.Cells[0].String(),
				Desc:         row.Cells[1].String(),
				Click:        0,
				Score:        4,
				FactoryPrice: 0,
				OutMinPrice:  OutMinPrice,
				OutMaxPrice:  OutMaxPrice,
				MainPicture:  GetMainImage(imageArray),
				CreatedAt:    CreatedAt,
				UpdatedAt:    CreatedAt,
				DeleteAt:     gorm.DeletedAt{},
				IsNew:        0,
				IsHot:        0,
				KeyWords:     tables.JSON(row.Cells[54].String()),
			}

			colors := splitColor2string(row.Cells[14].String(), row.Cells[15].String(), row.Cells[16].String(), row.Cells[17].String(), row.Cells[18].String(), row.Cells[19].String(), row.Cells[20].String(), row.Cells[21].String(), row.Cells[22].String(), row.Cells[23].String())

			Price2Temp, _ := row.Cells[66].Float()
			Price2 := int32(Price2Temp * 100)

			Price3Temp, _ := row.Cells[66].Float()
			Price3 := int32(Price3Temp * 100)

			Price4Temp, _ := row.Cells[68].Float()
			Price4 := int32(Price4Temp * 100)

			Price5Temp, _ := row.Cells[70].Float()
			Price5 := int32(Price5Temp * 100)

			Price6Temp, _ := row.Cells[72].Float()
			Price6 := int32(Price6Temp * 100)

			Price7Temp, _ := row.Cells[74].Float()
			Price7 := int32(Price7Temp * 100)

			ProductLengthTemp, _ := row.Cells[37].Float()
			ProductLengthTemp = checkFloat(ProductLengthTemp)
			ProductLength := int32(ProductLengthTemp * 100)

			ProductWidthTemp, _ := row.Cells[38].Float()
			ProductWidthTemp = checkFloat(ProductWidthTemp)
			ProductWidth := int32(ProductWidthTemp * 100)

			ProductHeightTemp, _ := row.Cells[39].Float()
			ProductHeightTemp = checkFloat(ProductHeightTemp)
			ProductHeight := int32(ProductHeightTemp * 100)

			ProductWeightTemp, _ := row.Cells[35].Float()
			ProductWeightTemp = checkFloat(ProductWeightTemp)
			ProductWeight := int32(ProductWeightTemp * 100)

			BoxLengthTemp, _ := row.Cells[43].Float()
			BoxLengthTemp = checkFloat(BoxLengthTemp)
			BoxLength := int32(BoxLengthTemp * 100)

			BoxWidthTemp, _ := row.Cells[44].Float()
			BoxWidthTemp = checkFloat(BoxWidthTemp)
			BoxWidth := int32(BoxWidthTemp * 100)

			BoxHeightTemp, _ := row.Cells[45].Float()
			BoxHeightTemp = checkFloat(BoxHeightTemp)
			BoxHeight := int32(BoxHeightTemp * 100)

			BoxNumberTemp, _ := row.Cells[41].Float()
			BoxNumberTemp = checkFloat(BoxNumberTemp)
			BoxNumber := int32(BoxNumberTemp * 100)

			BoxWeightTemp, _ := row.Cells[47].Float()
			BoxWeightTemp = checkFloat(BoxWeightTemp)
			BoxWeight := int32(BoxWeightTemp * 100)

			goodsDesc := tables.GoodsDesc{
				GoodsID:       GoodsID,
				Color:         colors,
				ProductLength: ProductLength,
				ProductWidth:  ProductWidth,
				ProductHeight: ProductHeight,
				ProductWeight: ProductWeight,
				BoxLength:     BoxLength,
				BoxWidth:      BoxWidth,
				BoxHeight:     BoxHeight,
				BoxNumber:     BoxNumber,
				BoxWeight:     BoxWeight,
				Material:      splitColor2string(row.Cells[24].String(), row.Cells[25].String(), row.Cells[26].String()),
				Image:         imageArray,
				Qty1:          50,
				Price1:        OutMaxPrice,
				Qty2:          100,
				Price2:        Price2,
				Qty3:          200,
				Price3:        Price3,
				Qty4:          500,
				Price4:        Price4,
				Qty5:          2000,
				Price5:        Price5,
				Qty6:          5000,
				Price6:        Price6,
				Qty7:          10000,
				Price7:        Price7,
				Qty8:          50000,
				Price8:        OutMinPrice,
			}

			// 插入数据
			dbB := db.Begin()
			result := dbB.Create(&goods)
			if result.Error != nil {
				log.Println(result.Error)
			}

			resultGoodsDesc := dbB.Create(&goodsDesc)
			if resultGoodsDesc.Error != nil {
				log.Println(result.Error)
			}
			dbB.Commit()
		}
	}

	fmt.Println("APMJ320-APMJ612.xlsx")
}
